package com.shaunstone.web.sports.rest;

import java.util.Iterator;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;

import com.shaunstone.web.sports.dal.dao.repo.PersonRepository;
import com.shaunstone.web.sports.dal.dao.repo.TeamRepository;
import com.shaunstone.web.sports.dal.model.Person;
import com.shaunstone.web.sports.dal.model.PersonTeamMapping;
import com.shaunstone.web.sports.dal.model.Team;

@RestController
public class PlayerEndpoint {

	private static final Logger LOGGER = LoggerFactory.getLogger(PlayerEndpoint.class);

	@Autowired
	TeamRepository teamRepository;

	@Autowired
	PersonRepository personRepository;

	@RequestMapping(value = "/rest/{teamid}/players", consumes = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.POST)
	@ResponseStatus(value = HttpStatus.CREATED)
	public String addPlayer(@RequestBody PersonTeamMapping person, @PathVariable("teamid") Integer teamid) {
		teamRepository.comst(person.getPerson(), person.getRole(), teamid);
		LOGGER.debug("here is the person now: {}", person);
		// return "redirect:{teamid}/coaches";
		return String.valueOf(person.getPerson().getId());
	}

	@RequestMapping(value = "/rest/{id}/players/{personid}", consumes = MediaType.ALL_VALUE, method = RequestMethod.DELETE)
	@ResponseStatus(value = HttpStatus.NO_CONTENT)
	@Transactional
	public void deletePlayer(@PathVariable("id") Team team, @PathVariable("personid") Integer personid) {
		Iterator<PersonTeamMapping> ptmi = team.getPersonTeamMappings().iterator();
		PersonTeamMapping pm = null;
		while (ptmi.hasNext()) {
			PersonTeamMapping personTeamMapping = ptmi.next();
			if (personTeamMapping.getPerson().getId() == personid) {
				pm = personTeamMapping;
				ptmi.remove();
				break;
			}
		}
		team.setName("WHATSUPCUZ");
//		team.removePersonTeamMapping(pm);
		teamRepository.save(team);
		
		// personRepository.delete(personid);
		// return "redirect:{teamid}/coaches";
	}

}
